<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Container from '@/components/Container/index.vue'
import TableComponent from '@/components/TableComponent/index.vue'
import {
  queryLabelList,
  insertLabel,
  updateLabel,
  removeLabel,
} from '@/api/labelManager'
import { columns } from './data'
import { formatTime } from '@/utils'
import InsertDialog from './components/insertDialog.vue'
import UpdateDialog from './components/updateDialog.vue'
import { ElMessage } from 'element-plus'
import type {
  LabelManager,
  LabelInsertManager,
  LabelUpdateManager,
  LabelRemoveManager,
} from '@/api/interface/labelManager'

defineOptions({
  name: 'LabelManager',
})

// 获取数据列表
const loading = ref(false)
const data = ref<LabelManager.Result[]>([])
const queryList = async () => {
    loading.value = true
    const result = await queryLabelList()
    loading.value = false
    // console.log('label list', result)
    data.value = result.map(item => ({
        ...item,
        createdAt: formatTime(item.createdAt),
        updatedAt: formatTime(item.updatedAt),
    }))
}
onMounted(queryList)

const updateData = ref<LabelManager.Result | null>(null)
const insertDialogRef = ref<InstanceType<typeof InsertDialog> | null>(null)
const updateDialogRef = ref<InstanceType<typeof UpdateDialog> | null>(null)

const handleInsert = async (data: LabelInsertManager) => {
  await insertLabel(data)
  ElMessage.success('新增标签成功')
  queryList()
}

const handleUpdate = async (data: LabelUpdateManager) => {
  await updateLabel(data)
  ElMessage.success('更新标签成功')
  queryList()
}

const handleRemove = async (data: LabelRemoveManager) => {
  await removeLabel(data)
  ElMessage.success('删除标签成功')
  queryList()
}

const openInsertDialog = () => {
  insertDialogRef.value?.open()
}

const openUpdateDialog = (data: LabelManager.Result) => {
  updateData.value = data
  updateDialogRef.value?.open()
}
</script>

<template>
  <Container
    class="label-manager"
    title="标签管理"
    search
    :columns="['add']"
    @on:add="openInsertDialog"
    v-loading="loading"
  >
      <TableComponent :is-pagination="false" :columns="columns" :initial="data">
          <template #tagColor="{ scope: { row } }">
              <div :style="{width: '25px', height: '25px', margin: '0 auto',borderRadius: '5px', backgroundColor: row.color}">
              </div>
          </template>
          <template #action="{ scope: { row } }">
              <el-button type="primary" link @click="openUpdateDialog(row)">编辑</el-button>
              <el-button type="danger" link @click="handleRemove(row)">
                  删除
              </el-button>
          </template>
      </TableComponent>
  </Container>
  <InsertDialog ref="insertDialogRef" @on:submit="handleInsert" />
  <UpdateDialog
    ref="updateDialogRef"
    @on:submit="handleUpdate"
    :data="updateData"
  />
</template>

<style scoped lang="scss">
.label-manager {
  width: 100%;
}
</style>
